package com.lh.controller;

import com.lh.commonutils.R;
import com.lh.service.IMsmService;
import com.lh.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private IMsmService iMsmService;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
//        1.从reids获取验证码，如果获取直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
//        生成随机数，传递到阿里云上
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
//        调用service中的方法
        boolean isSend = iMsmService.send(param, phone);
        if (isSend) {
//           key value  时间  时间单位
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }


}
